package com.wiki.KBS.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wiki.KBS.domian.Category;
import com.wiki.KBS.domian.CategoryExample;
import com.wiki.KBS.mapper.CategoryMapper;
import com.wiki.KBS.request.CategoryReq;
import com.wiki.KBS.request.CategorySaveReq;
import com.wiki.KBS.response.CategoryQueryResp;
import com.wiki.KBS.response.PageResp;
import com.wiki.KBS.utils.CopyUtil;
import com.wiki.KBS.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SnowFlake snowFlake;

    public List<CategoryQueryResp> categoryAll(){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");    // 设置排序条件
        // 把查询结果存入Category类型的列表里面
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> categoryQueryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        return  categoryQueryResps;
    }


    public PageResp<CategoryQueryResp> categoryList(CategoryReq req){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");    // 设置排序条件
        //  创建查询条件
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        // 把查询结果存入Category类型的列表里面
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> categoryQueryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        // 查询页面信息
        PageInfo<Category> PageInfo = new PageInfo<>(categoryList);
        log.info("总行数：{}",PageInfo.getTotal());
        log.info("总页数：{}",PageInfo.getPages());

        PageResp<CategoryQueryResp> PageResp = new PageResp<>();
        PageResp.setTotal(PageInfo.getTotal());
        PageResp.setList(categoryQueryResps);
        return  PageResp;
    }

    /**
     * 保存
     */
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        } else {
            // 更新
            log.info("总行数：{}",category);
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    public void delete(Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }
}
